package com.guojian.jdbc.mapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;

import com.google.common.collect.Maps;
import com.guojian.common.utils.StringUtilsx;

/**
 * 
 * @see @ObjectMapRowMapper  
 * 
 * @author GuoJian
 *
 */
@Deprecated
public class ColumnMapDataFormatRowMapper implements RowMapper<Map<String, Object>> {

	/**
	 * 是否增加驼峰似的名字USER_ID->userId
	 */
	private boolean isAddLowerCaseOfName = false;

	public ColumnMapDataFormatRowMapper() {
	}

	public ColumnMapDataFormatRowMapper(boolean isAddLowerCaseOfName) {
		this.isAddLowerCaseOfName = isAddLowerCaseOfName;
	}

	@Override
	public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map<String, Object> mapOfColumnValues = createColumnMap(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			String columnName = JdbcUtils.lookupColumnName(rsmd, i);
			Object columnValue = getColumnValue(rs, i);
			mapOfColumnValues.putIfAbsent(columnName, columnValue);
			if (isAddLowerCaseOfName) {
				mapOfColumnValues.putIfAbsent(StringUtilsx.toLowerCaseOfCamel(columnName), columnValue);
			}
		}
		return mapOfColumnValues;
	}

	/**
	 * @param columnCount
	 * @return
	 */
	protected Map<String, Object> createColumnMap(int columnCount) {
		if (isAddLowerCaseOfName) {
			return Maps.newLinkedHashMap();
		}
		//LinkedCaseInsensitiveMap 不区分大小写,会互相覆盖,取值同理
		return new LinkedCaseInsensitiveMap<>(columnCount);
	}

	protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
		return JdbcUtils.getResultSetValue(rs, index);
	}

	public static void main(String[] args) {

		// Map<String, Object> rowMap = new LinkedCaseInsensitiveMap<>();
		// rowMap.put("PROJECTNAME", "AAAAAAAAAAAAA");

		Map<String, Object> rowMap = new LinkedHashMap<>();
		rowMap.put("projectname", "AAAAAAAAAAAAA1");
		rowMap.put("PROJECTNAME", "AAAAAAAAAAAAA2");

		Map<String, Object> newRowMap = Maps.newConcurrentMap();
		newRowMap.put("projectname", "aaaaaaaaaaaaaaaaaaaaaaa");

		rowMap.putAll(newRowMap);
		//System.out.println("JSON.toJSONString(rowMap) = " + JSON.toJSONString(rowMap));

		Map<String, Object> nocasemap = new LinkedCaseInsensitiveMap<>();

		nocasemap.put("a", "1a00");
		nocasemap.put("A", "1A00");

		System.out.println(nocasemap.get("a"));
		System.out.println(nocasemap.get("A"));

	}
}
